package com.panda.utils;

import com.panda.pojo.Block;
import com.panda.pojo.Element;

import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

class InputUtils {

    //被输入的可能不是某个变量,而是一个对象中的某个变量
    private static Pattern ip = Pattern.compile("(__element_[0-9a-z_]+)[\n ]*>>[\n ]*([$]?[a-zA-Z]+[a-zA-Z0-9]*([ \n]*\\.[ \n]*[a-zA-Z]+[a-zA-Z0-9]*)?)");

    //右侧的一律视为变量,左侧的则为需要输入值的内容
    static String transformInput(Element element, String s, List<ParseUtils.AfterParseScript> afterParseScripts) {

        if ("".equals(s)) {
            return s;
        }


        Matcher matcher = ip.matcher(s);

        List<Block> subElement = element.getSubBlocks();


        while (matcher.find()) {

            String r = matcher.group();

            String id = matcher.group(1);

            String param = matcher.group(2).trim();

            afterParseScripts.add(() -> {

                //打包为解析完脚本后的后发指令
                for (Block block : subElement) {

                    if (block instanceof Element) {

                        if (block.getId().equals(id)) {

                            Map<String, String> attributes = ((Element) block).getAttributes();

                            Map<String, Integer> params = element.getScope().getAllParams();

                            Integer integer = params.get(param);

                            if (integer == null) {

                                integer = Integer.MAX_VALUE;

                                if (param.contains(".")) {

                                    for (String key : params.keySet()) {

                                        if (param.startsWith(key + ".")) {
                                            Integer v = params.get(key);
                                            if (v < integer) {
                                                integer = v;
                                            }
                                        }

                                    }

                                }

                                if (integer == Integer.MAX_VALUE) {
                                    integer = 0;
                                }

                            }

                            String ps = "";

                            for (int i = 0; i < integer; i++) {
                                ps += "$parent.";
                            }

                            attributes.put("ng-model", ps + param);

                            break;
                        }

                    }
                }

            });

            //并没有替换完全
            s = s.replace(r, "");

        }


        return s;


    }


}
